
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include <string>
using std::string;

#include "HTTPresponse.h"
#include "httputil.h"

bool HTTPResponse::parseFromfd(int sockfd)
{
    m_responseBytes.clear();
    string headLine;
    bool eof, success;
    success = HTTPUtil::readline(headLine, &eof, sockfd);
    if (!success) return false;
    success = m_headers.parseHeader(sockfd);
    if (!success) return false;
    if (!m_headers.isFieldExists("Content-Length"))
        return false;
    int length = atoi(m_headers.getFieldValue("Content-Length").c_str());
    char buf[256];ssize_t nread, nask;
    while (length) {
        nask = length < 256 ? length : 256;
        nread = read(sockfd, buf, nask);
        if (nread == -1) {
            perror("parseFromfd");
            return false;
        }
        if (nread == 0)
            break;
        length -= nread;
        m_responseBytes.append(buf, nread);
    }
    m_success = true;
    return true;
}
